package com.leiduoduo.oms.controller;


import com.alibaba.fastjson.JSONObject;
import com.leiduoduo.oms.annotation.PassToken;
import com.leiduoduo.oms.annotation.UserLoginToken;
import com.leiduoduo.oms.pojo.Token;
import com.leiduoduo.oms.pojo.User;
import com.leiduoduo.oms.service.UserService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@RestController
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;
    Logger logger = Logger.getLogger(UserController.class);

    @GetMapping("/getUserByCode/{app_code}")
    @HystrixCommand(fallbackMethod = "getUserByCodeHystrix")//只要mapper执行的流程中出现了一个错误（500）就会调用对应的fallbackMethod
    @PassToken
    public User getUserByCode(@PathVariable("app_code") String app_code){
        if (null == app_code){
            throw new RuntimeException(app_code);
        }
        User user = userService.getUserByCode(app_code);
        return user;
    }
    public User getUserByCodeHystrix(@PathVariable("app_code") String app_code){
        User user = new User();
        user.setApp_code(null);
        user.setName("用户不存在，请修改后重试");
        user.setDb_source("no database");
        return user;
    }

    @PostMapping("/addUser")
    @HystrixCommand(fallbackMethod = "addUserHystrix")
    @PassToken
    public boolean addUser(User user){
        return userService.addUser(user);
    }
    public boolean addUserHystrix(User user){
        return false;
    }

    @GetMapping("/getUserList")
    @HystrixCommand(fallbackMethod = "getUserList")
    @PassToken
    public List<User> getUserList(){
        return userService.getUserList();
    }
    public List<User> getUserListHystrix(){
        List<User> list = new LinkedList<User>();
        User user = new User();
        user.setId(0);
        user.setName("服务已崩，我们会尽快通知管理员，请稍后重试");
        user.setDb_source("no database");
        list.add(user);
        return list;
    }
    @RequestMapping(value = "/pic",method = RequestMethod.POST)
    @HystrixCommand(fallbackMethod = "uploadPic")
    @PassToken
    public String uploadPic(@RequestParam (value = "pic",required = false) MultipartFile pic, HttpServletRequest req){
        return userService.uploadPic(pic ,req);
    }
    public String uploadpicHystrix(){
        return "服务已崩，我们会尽快通知管理员，请稍后重试";
    }

    @GetMapping(value = "/getImage")
    @HystrixCommand(fallbackMethod = "downpicHystrix")
    @PassToken
    public void getImage(HttpServletResponse response) throws IOException {
        OutputStream os = null;
        try {
//        读取图片
            BufferedImage image = ImageIO.read(new FileInputStream(new File(ResourceUtils.getURL("classpath:").getPath() + "static/upload/" + "1608184766461_Personal.jpg")));
            response.setContentType("image/png");
            os = response.getOutputStream();

            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (IOException e) {
            logger.error("获取图片异常{}");
        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
    }
    public void downpicHystrix(HttpServletResponse response){

    }

    @RequestMapping(value = "/upUser",method = RequestMethod.POST)
    @HystrixCommand(fallbackMethod = "upUserHystrix")
    @PassToken
    public boolean upUser(User user){
        return userService.upUser(user);
    }
    public boolean upUserHystrix(User user){
        return false;
    }

    @RequestMapping(value = "/delUser",method = RequestMethod.POST)
    @HystrixCommand(fallbackMethod = "delUserHystrix")
    @PassToken
    public boolean delUser(User user){
        return userService.delUser(user);
    }
    public boolean delUserHystrix(User user){
        return false;
    }

    //测试token
    @GetMapping("/token")
    @UserLoginToken
    public boolean token(){
        return true;
    }

    @GetMapping("/testAsync")
    @PassToken
    public String testAsync() throws ExecutionException, InterruptedException {
        return userService.test().get();
    }

}
